/*
 * Copyright 2011 Clean GWT
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cleangwt.json.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONValue;

/**
 * The generic json deserializer.
 * 
 * @author Jess
 * @version 1.0
 * @since 1.0
 */
public class ObjectDeserializer extends JsonValueDeserializer<Object> {

  private static ObjectDeserializer impl;

  /**
   * @return the instance of gereric deserializer
   */
  public static ObjectDeserializer get() {
    if (impl == null) {
      impl = new ObjectDeserializer();
    }
    return impl;
  }

  private ObjectDeserializer() {
  }

  @Override
  public Object fromJson(JSONValue jsonValue) {
    if (jsonValue == null || jsonValue.isNull() != null) {
      return null;
    }
    if (jsonValue.isString() != null) {
      return jsonValue.isString().stringValue();
    } else if (jsonValue.isNumber() != null) {
      return jsonValue.isNumber().doubleValue();
    } else if (jsonValue.isBoolean() != null) {
      return jsonValue.isBoolean().booleanValue();
    } else if (jsonValue.isArray() != null) {
      JSONArray jsonArray = jsonValue.isArray();
      List<Object> collection = new ArrayList<Object>();
      for (int i = 0; i < jsonArray.size(); i++) {
        collection.add(fromJson(jsonArray.get(i)));
      }
      return collection;
    } else {
      return SimpleObjectDeserializer.get().fromJson(jsonValue);
    }
  }

}
